<template>
  <div class="good-operate wap">
    <div class="back display-flex align-items-center justify-content-flex-center">
      <x-icon @click.stop="goBack" type="ios-arrow-left" size="25"></x-icon>
    </div>
    <div class="main">
      <scroller>
        <div>
          <div class="swiper-container" v-if="goodInfo.pics">
            <swiper
              @click.native="showPic"
              height="320px"
              :show-dots="false"
              loop
              :list="goodInfo.pics"
              @on-index-change="swiperIndexChange"
            ></swiper>
            <div class="page-index">
              <span class="active">{{imgIndex+1}}</span>
              <span class="total">/{{goodInfo.pics.length}}</span>
            </div>
          </div>
          <div class="good-info">
            <div class="price display-flex align-items-center">
              <span
                v-if="getTejiaTip(goodInfo.activityGoodsVOList)"
                class="activity-tip display-flex justify-content-flex-center align-items-center"
              >特价</span>
              <div class="display-flex" v-if="goodInfo.enquiry==0">
                <!--<div class="jian flex-1" v-for="(price,index) in goodInfo.unitVOList" :key="price.id">-->
                <div class="jian" v-for="(price,index) in goodInfo.unitVOList" :key="price.id">
                  <div>
                    <span v-if="price.unitGoodsPricesVO">
                      <span class="symbol">￥</span>
                      <span
                        class="money"
                      >{{price.unitGoodsPricesVO.discountTaxPrice?price.unitGoodsPricesVO.discountTaxPrice:(price.unitGoodsPricesVO.taxPrice?price.unitGoodsPricesVO.taxPrice:'')}}</span>
                      <span class="unit">/{{price.unitGoodsPricesVO.unitName}}</span>
                      <span
                        class="line-througth"
                        v-if="price.unitGoodsPricesVO.discountTaxPrice"
                      >￥{{price.unitGoodsPricesVO.taxPrice}}/{{price.unitGoodsPricesVO.unitName}}</span>
                    </span>
                  </div>
                </div>
              </div>
              <div v-if="goodInfo.enquiry==1">
                <span class="enquiry-tip">询价</span>
              </div>
            </div>
            <div class="limit-tip">{{getLimintTip(goodInfo.unitVOList)}}</div>

            <div
              class="good-name vux-1px-b"
            >[{{goodInfo.brandName}}]{{goodInfo.name}}{{goodInfo.spec}}</div>
            <div class="recomment display-flex" v-if="goodInfo.memo">
              <div class="title">推荐</div>
              <div class="content flex-1">{{goodInfo.memo}}</div>
            </div>
          </div>
          <div v-if="goodInfo.activityGoodsVOList">
            <div v-for="(activity,index) in goodInfo.activityGoodsVOList" :key="activity.id">
              <div class="activity display-flex" v-if="activity.type==10">
                <div class="title">促销</div>
                <div class="content flex-1 display-flex">
                  <span class="tip display-flex justify-content-flex-center align-items-center">
                    <span>{{activity.type==1?'特价':activity.type==10?'搭赠':''}}</span>
                  </span>
                  <div class="tip-content flex-1" v-html="getActivityInfo(activity)"></div>
                </div>
              </div>
            </div>
          </div>

          <div class="detail">
            <div class="title">商品详情</div>
            <div>
              <x-table :full-bordered="true">
                <thead>
                  <tr>
                    <th colspan="2">厂家</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>
                      <span class="label">品牌:</span>
                      <span class="content">{{goodInfo.brandName}}</span>
                    </td>
                    <td>
                      <span class="label">规格:</span>
                      <span class="content">{{goodInfo.spec}}</span>
                    </td>
                  </tr>

                  <tr>
                    <td>
                      <span class="label">原产地:</span>
                      <span class="content">{{goodInfo.originArea}}</span>
                    </td>
                    <td>
                      <span class="label">加工方式:</span>
                      <span class="content">{{goodInfo.processMethod}}</span>
                    </td>
                  </tr>

                  <tr>
                    <td>
                      <span class="label">储存方法:</span>
                      <span class="content">{{goodInfo.store}}</span>
                    </td>
                    <td>
                      <span class="label">保质期:</span>
                      <span class="content">{{goodInfo.shelfLife}}</span>
                    </td>
                  </tr>
                  <tr>
                    <td>
                      <span class="label">商品编号:</span>
                      <span class="content">{{goodInfo.code}}</span>
                    </td>
                    <td>
                      <span class="label">QS号:</span>
                      <span class="content">{{goodInfo.qs}}</span>
                    </td>
                  </tr>
                </tbody>
              </x-table>
            </div>
            <!-- <div class="html-content" v-html="goodInfo.memo"></div>-->
          </div>
        </div>
      </scroller>
    </div>
    <div class="footer display-flex vux-1px-t">
      <div class="flex-1 display-flex" @click.stop="goShop">
        <div
          class="item flex-1 display-flex align-items-center justify-content-flex-center flex-direction-column"
        >
          <img src="../../assets/img/customer/dianpu.png" alt />
          <p>店铺</p>
        </div>
        <div
          @click.stop="goShopInfo"
          class="item flex-1 display-flex align-items-center justify-content-flex-center flex-direction-column"
        >
          <img src="../../assets/img/customer/lianxi.png" alt />
          <p>联系商家</p>
        </div>
        <div
          @click.stop="goCart"
          class="item flex-1 display-flex align-items-center justify-content-flex-center flex-direction-column"
        >
          <img src="../../assets/img/customer/gouwuche.png" alt />
          <p>购物车</p>
          <span
            class="good-num display-flex justify-content-flex-center align-items-center"
            v-if="numCount>0"
          >{{numCount}}</span>
        </div>
      </div>
      <div
        :class="['btn-add-good display-flex justify-content-flex-center align-items-center',]"
        @click="showPop"
      >加入购物车</div>
      <!--goodInfo.enquiry==1?'btn-disable':''-->
    </div>

    <div v-transfer-dom>
      <popup v-model="dialog" height="55%">
        <div class="popup-container wap">
          <img class="close" src="../../assets/img/customer/close_popup.png" alt @click="closePop" />
          <div class="main">
            <div class="good-num-container display-flex">
              <div class="title">购买数量</div>
              <div class="num-operate flex-1">
                <div
                  class="operate-item display-flex justify-content-flex-end align-items-center"
                  v-for="(item,index) in unitInfo"
                  :key="item.id"
                >
                  <span class="unit">{{item.name}}</span>
                  <AddReduceBtn useType="1" :goodId="goodId" :item="item"></AddReduceBtn>
                </div>
              </div>
            </div>
          </div>
          <div
            class="btn-comfirm display-flex justify-content-flex-center align-items-center"
            @click="addCart"
          >确定</div>
        </div>
      </popup>
    </div>
    <imgPreview v-if="goodInfo.pics" :picList="goodInfo.pics" ref="preview"></imgPreview>
  </div>
</template>
<script type="text/ecmascript-6">
import AddReduceBtn from "../../components/add-reduce-btn.vue";
import imgPreview from "../../components/img-preview.vue";
import { Storage } from "@/service/storage";

let fromPage;

export default {
  components: {
    AddReduceBtn,
    imgPreview,
  },
  data() {
    return {
      dialog: false,
      imgIndex: 0,
      goodInfo: {},
      numCount: 0,
      distributor: {},
      phone: "",
      unitInfo: [],
      goodId: "",
      sellerId: "",
    };
  },
  created() {
    this.goodId = this.$route.query.goodId || this.$route.query.id;
    this.initData();
  },
  mounted() {
    this.$callJava({ onBackPressed: true });
    this.oldOnBackPressed = window["onBackPressed"];
    window["onBackPressed"] = this.goBack.bind(this);
  },
  destroyed() {
    // this.$vux.toast.text("likai", 'center');
    window["onBackPressed"] = this.oldOnBackPressed;
    this.$callJava({ onBackPressed: false });
  },
  beforeRouteEnter(to, from, next) {
    fromPage = from;
    next();
  },
  methods: {
    // androidCallJs(val){
    //   alert("111")
    // },
    initData() {
      this.$ajax.get(
        "replenish/goods/detail",
        (res) => {
          if (res.code == 200) {
            this.sellerId = res.data.sellerId;
            this.initSellerPhone(this.sellerId);
            this.initGoodNum(this.sellerId);
            this.goodInfo = res.data;
            this.goodInfo.pics = [];
            for (let i = 0; i < res.data.goodsPicVOList.length; i++) {
              this.goodInfo.pics[i] = { img: res.data.goodsPicVOList[i] };
            }
            this.shareInit();
            this.initUnitInfo();
          } else {
            this.$vux.toast.text(res.msg, "center");
          }
        },
        { goodsId: this.goodId }
      );
    },
    goShopInfo() {
      if (Storage.get("token")) {
        if (this.$fromApp(this)) {
          // this.$router.push({path:'/shop/info',query:{shopId:this.shopId,from:'app'}})
          this.$callJava({
            url: this.$webUrl + "shop/info?from=app&shopId=" + this.sellerId,
            title: "店铺详情",
          });
        } else {
          this.$router.push({
            path: "/shop/info",
            query: { shopId: this.sellerId },
          });
        }
      }
    },
    initGoodNum(sellerId) {
      this.$ajax.get(
        "replenish/shopping_cart/num",
        (res) => {
          console.log("====nums", res);

          if (res.code == 200) {
            this.numCount = res.data;
          } else {
            this.$vux.toast.text(res.msg, "center");
          }
        },
        { goodsId: this.goodId, sellerId: sellerId }
      );
    },
    initSellerPhone(id) {
      this.$ajax.get(
        "common/distributor/info",
        (res) => {
          if (res.code == 200) {
            this.distributor = res.data;
            this.phone = res.data.phone;
          }
        },
        { distributorId: id }
      );
    },
    initUnitInfo() {
      this.$ajax.get(
        "common/distributor/info",
        (res2) => {
          if (res2.code == "200") {
            console.log("经销商信息：", res2);
            this.shopZeroSaleState = res2.data.zeroSaleFlag;

            if (this.$storage.get("token")) {
              this.$ajax.get(
                "replenish/goods/shopping_cart/info",
                (res) => {
                  console.log("====res==unit-info", res);
                  if (res.code == 200) {
                    for (let i = 0; i < res.data.length; i++) {
                      if (
                        (res.data[i].zeroSaleFlag == 0 ||
                          res.data[i].zeroSaleFlag == null) &&
                        this.shopZeroSaleState == 0
                      ) {
                        res.data[i].stockFlag = false;
                      } else {
                        res.data[i].stockFlag = true;
                      }
                    }
                    this.unitInfo = res.data;
                  } else {
                    this.$vux.toast.text(res.msg, "center");
                  }
                },
                { goodsId: this.goodId }
              );
            }
          }
        },
        { distributorId: this.sellerId }
      );
    },
    swiperIndexChange(index) {
      this.imgIndex = index;
    },
    showPop() {
      if (this.$storage.get("token")) {
        // if (this.goodInfo.enquiry == 1) {
        //   console.log("XXXXX");
        //   return;
        // }
        this.dialog = true;
      } else {
        this.$router.push({
          path: "/login",
          query: { sellerId: this.goodInfo.sellerId },
        });
      }
    },
    closePop() {
      this.dialog = false;
    },
    getLimintTip(unitVOList) {
      if (!unitVOList) {
        return "";
      } else {
        let str = "";
        for (let i = 0; i < unitVOList.length; i++) {
          if (
            unitVOList[i].unitGoodsPricesVO &&
            unitVOList[i].unitGoodsPricesVO.limitNum &&
            unitVOList[i].unitGoodsPricesVO.limitNum > 0
          ) {
            str =
              str +
              "第" +
              (unitVOList[i].unitGoodsPricesVO.limitNum + 1) +
              unitVOList[i].unitGoodsPricesVO.unitName +
              "起￥" +
              unitVOList[i].unitGoodsPricesVO.taxPrice +
              "/" +
              unitVOList[i].unitGoodsPricesVO.unitName;
            if (i != unitVOList.length - 1) {
              str += ",";
            }
          }
        }
        return str;
      }
    },
    getActivityInfo(activity) {
      if (activity.type == 10) {
        let head = "活动商品";
        let content = "";
        let array = activity.activityFullRuleVOList;
        for (let i = 0; i < array.length; i++) {
          let item = "";
          if (array[i].giveRule == 0) {
            item += "满";
          } else if (array[i].giveRule == 1) {
            item += "每满";
          }
          item +=
            array[i].num +
            "件赠" +
            "<span style='font-weight: bold'>[</span>" +
            array[i].brandName +
            "<span style='font-weight: bold'>]</span>" +
            array[i].goodsName +
            array[i].giftNum +
            array[i].unitName;
          if (i != array.length - 1) {
            item = item + ",";
          }
          content = content + item;
        }
        content = content + "数量有限,送完即止";
        head =
          head +
          content +
          "<br/><span style='margin-right: .1rem'>活动时间:</span>" +
          activity.beginTime.substr(0, 11) +
          "至" +
          activity.endTime.substr(0, 11);
        return head;
      }
      return "";
    },
    getTejiaTip(obj) {
      if (!obj) {
        return false;
      } else {
        for (let i = 0; i < obj.length; i++) {
          if (obj[i].type == 1) {
            return true;
            break;
          }
        }
      }
      return false;
    },
    callUser() {
      if (this.$storage.get("token")) {
        let phone = this.distributor.servicePhone;
        if (this.$fromApp(this)) {
          this.$callJava({ code: 1001, phone: phone });
        } else {
          window.location.href = "tel:" + phone;
        }
      } else {
        this.$router.push({
          path: "/login",
          query: { sellerId: this.goodInfo.sellerId },
        });
      }
    },
    showPic() {
      this.$refs.preview.show(this.imgIndex);
    },
    goShop() {
      if (this.$fromApp(this)) {
        this.$router.push({
          path: "/purchase/storePage?isQrShare=1&from=app",
          query: { id: this.goodInfo.sellerId },
        });
      } else {
        this.$router.push({
          path: "/purchase/storePage?isQrShare=1&",
          query: { id: this.goodInfo.sellerId },
        });
      }
    },
    goCart() {
      if (this.$storage.get("token")) {
        if (this.$fromApp(this)) {
          this.$router.push({
            path: "/cart?from=app",
            query: { id: this.goodInfo.sellerId },
          });
        } else {
          this.$router.push({
            path: "/cart",
            query: { id: this.goodInfo.sellerId },
          });
        }
      } else {
        this.$router.push({
          path: "/login",
          query: { sellerId: this.goodInfo.sellerId },
        });
      }
    },
    addCart() {
      let count = 0;
      for (let i = 0; i < this.unitInfo.length; i++) {
        if (this.unitInfo[i].num >= 0) {
          this.$ajax.post(
            "replenish/shopping_cart/setting",
            {
              goodsId: this.goodId,
              unitId: this.unitInfo[i].id,
              num: this.unitInfo[i].num,
            },
            (res) => {
              if (res.code == 200) {
                count++;
                if (count == this.unitInfo.length) {
                  //  this.$vux.toast.text("添加成功", 'center');
                  this.dialog = false;
                  this.initGoodNum(this.sellerId);
                }
                console.log(this.unitInfo)
              } else {
                if (count == 0) {
                  this.dialog = false;
                  this.$vux.toast.text(res.msg, "center");
                }
              }
            }
          );
        }
      }
    },
    goBack() {
      // alert("222")
      // this.$callJava({code:1007})
      if (this.$route.query.fromPush || !fromPage || !fromPage.name) {
        this.$router.replace({
          path: "/index",
          query: {
            from: this.$fromApp(this) ? "app" : "",
            id: this.sellerId,
          },
        });
      } else {
        this.$router.go(-1);
      }
      // if (this.$fromApp(this)) {
      //   if(this.$route.query.fromPush){
      //     this.$callJava({code:1007})
      //   }else{
      //     this.$router.go(-1);
      //   }
      // } else {
      //   this.$router.go(-1);
      // }
    },
    isIos() {
      const u = navigator.userAgent;
      return u.indexOf("iPhone") > -1 || u.indexOf("Mac OS") > -1;
    },

    shareInit() {
      let _this = this;
      let url = "";
      if (this.isIos()) {
        url = window.location.href;
        url = url.split("#");
        url = url[0];
      } else {
        url = window.location.href;
      }

      let options = {
        url: url,
      };
      let isSpc = _this.getTejiaTip(_this.goodInfo.activityGoodsVOList);
      this.$ajax.post("wechat/signature/jsapi", options, (res) => {
        wx.config({
          debug: false,
          appId: res.data.appId,
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonceStr,
          signature: res.data.signature,
          jsApiList: [
            "checkJsApi",
            "onMenuShareTimeline",
            "onMenuShareAppMessage",
          ],
        });

        wx.ready(function () {
          wx.onMenuShareTimeline({
            title: `[${_this.goodInfo.brandName}]${_this.goodInfo.name}${
              _this.goodInfo.spec
            }${
              _this.goodInfo.enquiry == 0 && isSpc
                ? "，特价抢购中！"
                : _this.goodInfo.enquiry == 0 && !isSpc
                ? "，搭赠抢购中！"
                : ""
            }`, // 分享标题
            link: _this.$webUrl + "good/operate?goodId=" + _this.goodInfo.id,
            imgUrl: _this.goodInfo.goodsPicVOList[0] || "", // 分享图标
            success: function () {
              // 用户确认分享后执行的回调函数
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
            },
          });
          wx.onMenuShareAppMessage({
            title: `[${_this.goodInfo.brandName}]${_this.goodInfo.name}${
              _this.goodInfo.spec
            }${
              _this.goodInfo.enquiry == 0 && isSpc
                ? "，特价抢购中！"
                : _this.goodInfo.enquiry == 0 && !isSpc
                ? "，搭赠抢购中！"
                : ""
            }`, // 分享标题
            desc: "这商品实在太棒了!", // 分享描述
            link: _this.$webUrl + "good/operate?goodId=" + _this.goodInfo.id,
            imgUrl: _this.goodInfo.goodsPicVOList[0] || "", // 分享图标
            success: function () {
              // 用户确认分享后执行的回调函数
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
            },
          });
        });
      });
    },
  },
};
</script>

<style lang="less" type="text/less" scoped>
.good-operate {
  position: relative;

  .btn-disable {
    background: #999 !important;
    color: #fff !important;
  }

  .limit-tip {
    color: #e9573f;
    font-size: 0.28rem;
  }

  .enquiry-tip {
    color: #666;
    margin: 0.2rem 0rem;
    font-size: 0.34rem;
  }

  .back {
    position: absolute;
    width: 0.6rem;
    height: 0.6rem;
    padding: 0.05rem;
    border-radius: 100%;
    background: rgba(0, 0, 0, 0.4);
    top: 0.3rem;
    left: 0.3rem;
    z-index: 99;

    svg {
      fill: #fff;
    }
  }

  .swiper-container {
    position: relative;

    /deep/ .vux-slider > .vux-swiper > .vux-swiper-item > a > .vux-img {
      background-size: 100% 100% !important;
    }

    .page-index {
      position: absolute;
      bottom: 0.24rem;
      right: 0.3rem;
      background: #cbcbcb;
      border-radius: 0.2rem;
      height: 0.4rem;
      padding: 0 0.2rem;

      .active {
        font-size: 0.28rem;
        color: #222;
        font-weight: bold;
      }

      .total {
        font-size: 0.2rem;
        color: #666;
      }
    }

    /deep/ .vux-slider > .vux-swiper > .vux-swiper-item > a > .vux-swiper-desc {
      height: 0;
      background-image: none;
      padding: 0;
    }
  }

  .good-info {
    background: #fff;
    padding: 0 0.3rem;

    .jian {
      margin-right: 0.35rem;
    }

    .price {
      padding: 0.2rem 0;

      .activity-tip {
        min-width: 0.8rem;
        max-height: 0.35rem;
        padding: 0.01rem 0.02rem;
        font-size: 0.22rem;
        color: #e9573f;
        margin-right: 0.18rem;
        border-radius: 15px;
        border: 1px solid #e9573f;
        text-align: center;
      }

      .symbol {
        font-size: 0.34rem;
        color: #ff3c4a;
      }

      .money {
        font-size: 0.52rem;
        color: #ff3c4a;
      }

      .unit {
        font-size: 0.34rem;
        color: #666;
      }

      .line-througth {
        text-decoration: line-through;
        color: #bbb;
        margin-left: 0.1rem;
      }
    }
  }

  .good-name {
    font-size: 0.34rem;
    color: #333;
    padding-bottom: 0.3rem;
    font-weight: bold;
  }

  .recomment {
    padding-top: 0.2rem;
    padding-bottom: 0.3rem;

    .title {
      font-size: 0.26rem;
      color: #333;
      margin-right: 0.3rem;
      font-weight: bold;
    }

    .content {
      font-size: 0.26rem;
      color: #333;
    }
  }

  .activity {
    background: #fff;
    margin-top: 0.2rem;
    padding: 0.2rem 0.3rem;

    .title {
      font-size: 0.26rem;
      color: #333;
      margin-right: 0.3rem;
      font-weight: bold;
    }

    .content {
      font-size: 0.24rem;
      color: #333;
    }

    .tip {
      height: 0.3rem;
      padding: 0.03rem 0.15rem;
      font-size: 0.22rem;
      color: #e9573f;
      margin-right: 0.18rem;
      border-radius: 15px;
      border: 1px solid #e9573f;

      text-align: center;
    }
  }

  .detail {
    margin-top: 0.2rem;
    background: #fff;
    padding: 0.3rem 0.3rem;

    .title {
      font-size: 0.3rem;
      color: #333;
      margin-bottom: 0.6rem;
    }

    .vux-table {
      line-height: normal;
    }

    .vux-table td,
    .vux-table th {
      text-align: left;
      padding-left: 0.25rem;
      padding: 0.2rem;
    }

    .label {
      font-size: 0.26rem;
      color: #999;
      margin-right: 0.25rem;
    }

    .content {
      font-size: 0.26rem;
      color: #222;
      margin-right: 0.2rem;
    }

    .html-content {
      margin-top: 0.4rem;
    }
  }

  .footer {
    background: #fff;
    height: 1rem;

    .btn-add-good {
      min-width: 3.62rem;
      height: 100%;
      text-align: center;
      background: #527dd9;
      color: #fff;
      font-size: 0.34rem;
    }

    .item {
      position: relative;

      img {
        width: 0.44rem;
        height: 0.44rem;
      }

      p {
        font-size: 0.22rem;
        color: #333;
      }

      .good-num {
        box-sizing: border-box;
        position: absolute;
        right: 0.25rem;
        top: 0.04rem;
        color: #fff;
        padding: 0rem 0.08rem;
        border-radius: 0.13rem;
        height: 0.26rem;
        /*line-height: .26rem;*/
        text-align: center;
        background: #ff3c4a;
        z-index: 99;
        font-size: 0.16rem;
      }
    }
  }
}

/deep/ .vux-popup-dialog {
  background: none;
}

.popup-container {
  position: relative;
  background: #fff;
  border-top-left-radius: 0.3rem;
  border-top-right-radius: 0.3rem;
  height: 100%;

  .btn-comfirm {
    height: 1.02rem;
    text-align: center;
    color: #fff;
    font-size: 0.34rem;
    background: #527dd9;
  }

  .close {
    position: absolute;
    right: 0.3rem;
    top: 0.3rem;
    width: 0.4rem;
    height: 0.4rem;
    padding: 0.1rem 0.2rem;
    z-index: 99;
  }

  .title {
    font-size: 0.3rem;
    color: #333;
  }

  .good-num-container {
    padding: 1.66rem 0.3rem 0rem 0.3rem;

    .num-operate {
      .operate-item {
        margin-bottom: 0.5rem;
      }

      .unit {
        font-size: 0.3rem;
        color: #333;
        margin-right: 0.2rem;
      }
    }
  }
}
</style>
